/**
 * @brief    提取bdf中的所有卡片数据
 *  提示某bdf文件中包含的所有卡片数据，以及本程序未支持的词条
 * @version  0.1
 * @author   wuxingchuang
 * @date     2025.06.28
 */
#include <iostream>
#include <string>

#include <boost/algorithm/string.hpp>

#include "Utility/Logging/SGLogger.h"

#include "DBManager/DBServiceFactory.h"
#include "DBManager/Database/DatabaseFactory.h"

#include "Import/BDFImport/BDFImport.h"

using namespace SG::DBManager;
using namespace SG::Import;
using SG::DataStructure::Common::Status;

#ifdef _WIN32
#include <windows.h>
std::string OpenFileDialog ()
{
    char         szFile[MAX_PATH] = { 0 };
    OPENFILENAME ofn              = { 0 };
    ofn.lStructSize               = sizeof (OPENFILENAME);
    // ofn.hwndOwner = hwnd;
    /* 使用字符串数组来设定过滤器 */
    ofn.lpstrFilter = "BDF Files\0*.bdf\0All Files\0*.*\0";
    ofn.lpstrFile   = szFile;
    ofn.nMaxFile    = MAX_PATH;
    ofn.Flags       = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

    if (GetOpenFileName (&ofn))
    {
        return szFile;
    }
    return "@";
}
#endif

int main (int argc, char const* argv[])
{
    std::string filepath;
#ifdef _WIN32
    if (argc == 1)
    {
        filepath = OpenFileDialog ();
        if (filepath.empty () || filepath == "@")
        {
            return 1;
        }
    }
#endif

    if (argc == 2)
    {
        filepath = argv[1];
    }

    // filepath = "/home/wxc/SGSim/TestData/Import/BDF/SETTest.bdf";

    // 检查路径是否有效
    if (filepath.empty ())
    {
        std::cerr << "Error: No file path provided." << std::endl;
        return 1;
    }

    SG::Utility::SGLogger::get ().disable ();  // 禁用日志记录

    if (boost::ends_with (filepath, ".bdf"))
    {
        // 使用‘*’号输出友好的欢迎信息
        std::cout << "************************************************************" << std::endl;
        std::cout << "*                                                          *" << std::endl;
        std::cout << "*          Welcome to use the BDF card extractor !         *" << std::endl;
        std::cout << "*                                                          *" << std::endl;
        std::cout << "************************************************************" << std::endl;

        // 数据库工厂
        DatabaseFactory dbFactory;
        IDatabase*      db = dbFactory.GetDatabase (DatabaseFactory::HDF5, ".", "bdfce.db");
        // 根据数据库创建Service管理器
        auto dbManager = std::make_shared<DBServiceFactory> (db);
        dbManager->ClearDatabase ();

        auto _imp = std::make_shared<BDFImporter> (dbManager);
        if (_imp == nullptr)
        {
            std::cout << "failed to generate Importer .";
            return 1;
        }

        if (_imp->Load (filepath.c_str ()) != Status::STATUS_Success)
        {
            return 1;
        }
#ifdef _WIN32
        system ("pause");
#endif
    }
    return 0;
}
